package com.tjb.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tjb.reggie.entity.DishFlavor;
import com.tjb.reggie.entity.dto.DishDto;
import com.tjb.reggie.service.DishFlavorService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.tjb.reggie.common.R;
import com.tjb.reggie.entity.Category;
import com.tjb.reggie.entity.Dish;
import com.tjb.reggie.service.CategoryService;
import com.tjb.reggie.service.DishService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author tjb
 * @version 1.0
 * @date 2022/8/25 15:54
 */
@RestController
@RequestMapping("/dish")
public class DishController {
    /**
     * 菜品业务
     */
    @Resource
    private DishService dishService;
    /**
     * 分类业务
     */
    @Resource
    private CategoryService categoryService;
    /**
     * 口味业务
     */
    @Resource
    private DishFlavorService flavorService;
    /**
     * 缓存业务
     */
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto : 传输对象
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        //更新了就要删除他的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }
    @GetMapping("page")
    public R<Page<DishDto>> page(int page, int pageSize, String name){
        //1、查询所有的菜品,但是缺少了菜品分类
        Page<Dish> dishPage = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //条件编写
        wrapper.like(name!=null, Dish::getName, name);
        //排序
        wrapper.orderByAsc(Dish::getSort).orderByAsc(Dish::getCreateTime);
        //查询
        dishService.page(dishPage, wrapper);

        //2、查询出所有分类，查一次，用多次
        List<Category> categoryList = categoryService.list();

        //3、对象拷贝
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);
        //拷贝的时候，排除所有的记录
        BeanUtils.copyProperties(dishPage, dishDtoPage,"records");

        //4、对分类名称进行处理和封装
        List<Dish> records = dishPage.getRecords();
        List<DishDto> lists = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            for (Category category : categoryList) {
                if (dishDto.getCategoryId().equals(category.getId())){
                    dishDto.setCategoryName(category.getName());
                    break;
                }
            }
            return dishDto;
        }).collect(Collectors.toList());
        //5、重新赋值给records
        dishDtoPage.setRecords(lists);
        //6、 返回
        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getDishWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 更新菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        //更新了就要删除他的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }

    /**
     * 停售
     * @param ids
     * @return
     */
    @PostMapping("/status/0")
    public R<String> stopByIds(@RequestParam List<Long> ids){
        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(0);
            dishService.updateById(dish);
        }
        return R.success("停售成功");
    }
    /**
     * 起售
     * @param ids
     * @return
     */
    @PostMapping("/status/1")
    public R<String> startByIds(@RequestParam List<Long> ids){
        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(1);
            dishService.updateById(dish);
        }
        return R.success("起售成功");
    }
    @DeleteMapping
    public R<String> deleteByIds(@RequestParam List<Long> ids){
        dishService.deleteByIdsWithFlavor(ids);
        return R.success("删除成功");
    }

    /**
     * 根据条件，查询对应的菜品信息
     * @param dish
     * @return
     */
    @GetMapping("list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtos = null;
        //动态的构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //查询缓存
        dishDtos = (List<DishDto>)redisTemplate.opsForValue().get(key);
        if (dishDtos != null){
            return R.success(dishDtos);
        }
        //1.构造器
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //条件设置
        wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        wrapper.orderByAsc(Dish::getSort).orderByAsc(Dish::getCreateTime);
        //状态为1，正在售卖的商品
        wrapper.eq(Dish::getStatus, 1);
        List<Dish> list = dishService.list(wrapper);

        //2、查询菜品所有的口味
        List<DishFlavor> flavorList = flavorService.list();

        //3、封装每个菜品的口味
        dishDtos = list.stream().map((item) -> {
            //创建一个新的对象，进行返回
            DishDto dishDto = new DishDto();
            //赋值
            BeanUtils.copyProperties(item, dishDto);
            //口味的设置操作
            List<DishFlavor> dishFlavors = new ArrayList<>();
            for (DishFlavor dishFlavor : flavorList) {
                if (item.getId().equals(dishFlavor.getDishId())) {
                    dishFlavors.add(dishFlavor);
                }
            }
            //设置口味
            dishDto.setFlavors(dishFlavors);
            //返回
            return dishDto;
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(key, dishDtos, 60, TimeUnit.MINUTES);
        return R.success(dishDtos);
    }
}
